#include <stdio.h>
#include <stdlib.h>
#include <graphics.h>
#include <math.h>

#define WIDTHOFFSET 18
#define PIXELOFFSET 1078
#define PI 3.14159265

int width, height;
unsigned char huge pixel[640][640];

void getData(FILE *);
void display();

int main(void) {
	char imagename[30];
	printf("\n Enter the image..");
	// fflush(stdout);
	gets(imagename);
	FILE *fp = fopen(imagename, "rb");
	if (fp == NULL)
		printf("Error..");
	int gDriver = DETECT;
	int gMode;
	int errorcode;
	struct palettetype pal;
	initgraph(&gDriver, &gMode, "C:\\TURBOC3\\BGI\\");
	errorcode = graphresult();
	if (errorcode != grOk)
		printf("\n%s", grapherrormsg(errorcode));
	getpalette(&pal);

	//Create Grayscale
	for (int i = 0; i < pal.size; i++) {
		setrgbpalette(pal.colors[i], i * 4, i * 4, i * 4);
	}
	getData(fp);
	display();
	getchar();
	cleardevice();
	return 0;
}

void getData(FILE *fp) {
	unsigned long img_width, img_height;
	fseek(fp, WIDTHOFFSET, SEEK_SET);
	fread(&img_width, 4, 1, fp);
	fread(&img_height, 4, 1, fp);
	fseek(fp, PIXELOFFSET, SEEK_SET);

	width = (int) img_width;
	height = (int) img_height;
	for (int i = 0; i < height; i++) {
		for (int j = 0; j < width; j++) {
			if((atoi((const char*)fgetc(fp)))>70){
			pixel[i][j] = 0;}
			else{
		   pixel[i][j] = 255;
			}
		}
	}
}

void display() {
	settextstyle(1, 0, 3);
	outtextxy(250, 35, "Bitmap Image");
	for (int row = 0; row < height; row++) {
		for (int col = 0; col < width; col++) {
			putpixel(col, 500 - row, pixel[row][col] / 16);

		}

	}

}
